#include "../Loaders/OffLoader.h"
#include "../Core/ResourceManager.h"
#include "../Debug/Exceptions.h"
#include <string>
#include <fstream>

using namespace std;

namespace epix {

OffLoader::OffLoader()
{
}

OffLoader::~OffLoader()
{
}

Model *OffLoader::loadFromFile(const char *filename)
{
    ResourceManager *rsmgr = ResourceManager::instance();
    Model *model = rsmgr->get<Model>(filename);
    if(!model)
    {
        unsigned int nbVertices, nbIndices, nbbords;
        unsigned int *indices;
        float *vertices;
		int b;
		
        try
        {
			ifstream file (filename, ios::in);
			if(file)
			{
				string filetype;
				file >> filetype;
      
				if(filetype != "OFF")
					throw LoadingFailed(filename, "Wrong file format");
					
				file >> nbVertices >> nbIndices >> nbbords;

				vertices = new float[nbVertices*3];
				indices = new unsigned int[nbIndices*3];
				
				for (unsigned int i=0; i<nbVertices*3; i+=3)
					file >> vertices[i] >> vertices[i+1] >> vertices[i+2];
	     
				for (unsigned int j=0; j<nbIndices*3; j+=3)
				{
					file >> b;
					file >> indices[j] >> indices[j+1] >> indices[j+2];
				}
				model = new Model(filename, nbVertices*3, vertices, 0, NULL, 0, NULL, nbIndices*3, indices);
			}
			else
				throw LoadingFailed(filename, "Couldn't open file.");
        }
        catch(const exception &e)
        {
            Logger::log() << e.what() << "\n";
            model = NULL;
        }
    }
    return model;
}

}
